import ourcity.issues.models as im
import ourcity.reps.models as rm
import ourcity.utils.image_processing as ip

from django.contrib.auth.models import User
from django.contrib.comments.models import Comment
from django.contrib.localflavor.us.models import USStateField
from django.db import models

class Profile(models.Model):
    user = models.ForeignKey(User, unique=True, related_name='profile')
    address = models.CharField(max_length=128, blank=True)
    standardized_address = models.CharField(max_length=128, blank=True)
    city = models.CharField(max_length=64, blank=True)
    state = USStateField(blank=True)
    postal_code = models.CharField(max_length=32, blank=True) 
    latitude = models.FloatField(blank=True, null=True)
    longitude = models.FloatField(blank=True, null=True)
    photo = models.ImageField(upload_to='uploaded/user_photos', blank=True)
    districts = models.ManyToManyField(rm.District, blank=True)
    email_opt_in = models.BooleanField(default=True, help_text="Can we send you email updates about important news?")

    def __unicode__(self):
        return self.user.username

    def get_absolute_url(self):
        return ('profiles_profile_detail', (), 
                {'username': self.user.username})
    get_absolute_url = models.permalink(get_absolute_url)

    def save(self, *args, **kwargs):
        super(Profile, self).save(*args, **kwargs)
        if self.photo:
            ip.resize_image(self.photo.path, 100, 100)


class FeaturedContentManager(models.Manager):
    def active(self):
        return self.filter(active=True)


class FeaturedContent(models.Model):
    active = models.BooleanField(default=True)
    image = models.ImageField(upload_to='uploaded/featured_content')
    headline = models.CharField(max_length=64)
    # use CharField instead of URLField to allow relative links
    link = models.CharField(max_length=128, help_text='Relative, no leading slash. For example: "blog/6"')
    order = models.PositiveSmallIntegerField()

    objects = FeaturedContentManager()

    def __unicode__(self):
        return self.headline

    def save(self, *args, **kwargs):
        super(FeaturedContent, self).save(*args, **kwargs)
        ip.resize_image(self.image.path, 190, 190)

    class Meta:
        ordering = ('order', 'id')
        verbose_name_plural = 'featured content'


class FeaturedComment(models.Model):
    active = models.BooleanField(default=True)
    comment = models.ForeignKey(Comment)

    def __unicode__(self):
        return self.comment.__unicode__()

    class Meta:
        ordering = ('-id',)


class FeaturedIssue(models.Model):
    active = models.BooleanField(default=True)
    issue = models.ForeignKey(im.Issue)

    def __unicode__(self):
        return self.issue.__unicode__()

    class Meta:
        ordering = ('-id',)

